<?php

namespace Biz\model;

use Medoo\Medoo;


/**
 *
 * @author lee
 *
 */
class ShopSecurityDeposit extends \Doraemon\pockets\datebase\BaseDbModel
{

    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_shop_info';

    const _DATABASE_ = 'shop_info';

    const _TABLE_NAME = 'shop_security_deposit';

    const _SUB_TABLE = false;


    //保证金状态
    const STATUS_NOT_SET = 0;//未设置
    const STATUS_NOT_PAY = 1;//未交
    const STATUS_WAIT_CONFIRM = 2;//等待确认
    const STATUS_COMPLETE_DELIVERY = 3;//已完成

    //此状态无需存入数据库
    const STATUS_DEBT = 4;//欠款

    //保证金状态说明
    public static $statusDesc = [
        self::STATUS_NOT_SET => '未设置',
        self::STATUS_NOT_PAY => '未交',
        self::STATUS_WAIT_CONFIRM => '等待确认',
        self::STATUS_COMPLETE_DELIVERY => '已完成',
    ];

    public static $statusAdmSearchDesc = [
        self::STATUS_NOT_SET => '未设置',
        self::STATUS_NOT_PAY => '未交',
        self::STATUS_WAIT_CONFIRM => '等待确认',
        self::STATUS_COMPLETE_DELIVERY => '已完成',
        self::STATUS_DEBT => '欠款'

    ];


    //初始化保证金账户，一个用户只能初始化一次
    public static function mgtInitAccountData($uid)
    {
        try {
            $ret = self::insert([
                'shop_id' => $uid,
                'status' => self::STATUS_NOT_SET,
                'uid' => $uid,
            ]);

            if ($ret->errorCode() !== '00000') {
                throw new \Exception('保证金账户创建失败');
            }
        } catch (\Exception $e) {
            throw $e;
        }
    }


    /**
     * 通知管理员已支付保证金
     */
    public static function mgtNoticeManagePaid($uid)
    {
        self::update(['status' => self::STATUS_WAIT_CONFIRM], ['uid' => $uid]);


    }

    public static function getDepositList($uids)
    {
        $list = self::select("*", [
            "uid" => $uids
        ]);
        $formatData = [];
        foreach ($list as &$deposit) {

            self::formatInfo($deposit);

            $formatData[$deposit["uid"]] = $deposit;
        }

        return $formatData;
    }

    /**
     * @param $uid
     * @return mixed
     * 建议加到事务中
     */

    public static function getInfo($uid)
    {
        $info = self::select_master("*", Medoo::raw(' where uid=:uid for update', [':uid' => $uid]));

        $info = array_shift($info);

        self::formatInfo($info);

        return $info;
    }

    public static function formatInfo(&$info)
    {
        if (empty($info)) return;

        foreach ($info as $key => &$value) {
            switch ($key) {
                case 'status':
                    $info['status_desc'] = self::$statusDesc[$value];
                    break;
            }
        }
    }
}

